package com.jiang.daily.Q2799;

import java.util.*;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/04/24 11:19
 */
public class Solution {
    public int countCompleteSubarrays(int[] nums) {
//        Set<Integer> set = new HashSet<>();
//        int differ = 0;
//        for (int num : nums) {
//            if (!set.contains(num)) {
//                differ++;
//                set.add(num);
//            }
//        }
        int differ = new HashSet<>(Arrays.asList(Arrays.stream(nums).boxed().toArray(Integer[]::new))).size();
        Map<Integer, Integer> map = new HashMap<>();
        int res = 0, diff = 0, len = nums.length;
        for (int left = 0, right = 0; right < nums.length; right++) {
            int count = map.getOrDefault(nums[right], 0);
            if (count == 0) {
                diff++;
            }
            map.put(nums[right], count + 1);
            while (diff == differ) {
                res += len - right;
                int count1 = map.get(nums[left]);
                if (count1 == 1) {
                    diff--;
                }
                map.put(nums[left], count1 - 1);
                left++;
            }
        }
        return res;
    }
}
